<!--
 * @description  :
 * @descriptionDetail:
 * @copyright    : 浙江烟草
 * @author       : mhb
 * @create       : 2023-01-17 11:06:06
-->

<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :is-white="false" :title="navTitle" :custom-back="goBack" style="z-index: 99999">
      <view class="right-icon" @click="confirm">
        确定
      </view>
    </theme-navbar>
    <!-- #endif -->
		<!-- #ifdef H5-WECHAT || H5-EMP -->
		<fab-button :content="fContent" @fabtrigger="fabtrigger" />
		<!-- #endif -->
		<view class="m-content">
			<view :style="{width: getContainerWidth(), height: getContainerHeight()}" id="container"></view>
			<view class="cur-loc">
				<u-image :src="require('@/static/market/cur-loc-gree.png')" width="100%" mode="widthFix" @click="toCurrent"></u-image>
			</view>
			<view class="merge-loc" v-if="canDrag == true">
				<u-image :src="require('@/static/certificate/lc.png')" width="100%" mode="widthFix" @click="mergeCurrent"></u-image>
			</view>
			<view class="y-location">
				<text class="Lng">经度： {{ newPosition.lng }}</text>
				<text class="Lat">纬度： {{ newPosition.lat }}</text>
			</view>
			<view class="m-market" v-if="disable || canDrag == true">
				<u-row :gutter="16" class="padding-13">
					<u-col :span="12">{{ getRegeocodeInfo1() }}</u-col>
				</u-row>
				<u-row :gutter="16" class="pt-13">
					<u-col :span="12">{{ getRegeocodeInfo2() }}</u-col>
				</u-row>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		AMapMixin
	} from '@/common/AMapMixin.js';
	import {
		SET_MAP_LAT_LON
	} from '@/config/setting.config.js';
	// 截图工具类  fsx 2024-2-23 开始
	import {screenshots} from '@/common/ScreenshotsUtil.js';
	// 截图工具类  fsx 2024-2-23 结束
	import fabButton from '@/components/uni-fab.vue';


	export default {
		components: {
			fabButton
		},
		onLoad(opt) {
			this.canDrag = opt.canDrag == '0' ? false : true; // 0 表示不拖动  1表示拖动
			this.oldPosition = getApp().globalData.intentParams;
			this.newPosition.lng = this.oldPosition.lng || '';
			this.newPosition.lat = this.oldPosition.lat || '';
			// 是否开启截图  fsx 2024-2-23 开始
			this.isScreenshot = opt.isScreenshot || false;
			// 是否开启截图  fsx 2024-2-23 结束
			let obj = this.getRouteParam();
			// console.log(obj)
			this.disable = obj.disable;
			this.step = obj.step;
		},
		mixins: [AMapMixin],
		data() {
			return {
				canDrag: true,
				oldPosition: {},
				newPosition: {
					lng: '',
					lat: '',
				},
				currPosition: undefined,
				disable: '',
				step: '',
				positionPicker: undefined,
				fContent: [{
					iconPath: require('@/static/confirm.png'),
					selectedIconPath: require('@/static/confirm.png'),
					text: '确定',
					active: false,
				}],
				isScreenshot:false
			};
		},
		mounted() {
			this.init();
		},
		methods: {
			init() {
				this.setRightBtns();
				// this.$modal.showLoading('地图加载中...');
			},
			initAmap() {
				let self = this;
				// #ifdef H5-DINGDING || H5-WECHAT || H5-EMP
				this.$deviceApi.geolocation().then(
					(res) => {
						self.curPos = [res.longitude, res.latitude];
						self.setMapInstance([res.longitude, res.latitude]);
					},
					(err) => {
						self.justInitMap();
					}
				);
				// #endif
				// #ifdef H5-ONLY
				self.curPos = SET_MAP_LAT_LON;
				self.setMapInstance(SET_MAP_LAT_LON);
				// #endif
			},
			setRightBtns() {
				let self = this;
				// 设置右侧标题
				// #ifdef H5-DINGDING
				self.$deviceApi.setRight('确定', () => {
					self.confirm();
					self.setRightBtns();
				}, true, true);
				// #endif
			},
			fabtrigger(btn) {
				if (btn.index == 0) {
					this.confirm();
				}
			},
			getContainerHeight() {
				let p = this.$u.sys().windowHeight - 44 - this.$u.sys().statusBarHeight + 'px';
				// #ifdef H5-DINGDING || H5-WECHAT
				p = this.$u.sys().windowHeight - this.$u.sys().statusBarHeight + 'px';
				// #endif
				return p;
			},
			getContainerWidth() {
				return this.$u.sys().windowWidth + 'px';
			},
			toCurrent() {
				let self = this;
				self.$deviceApi.geolocation().then(
					(res) => {

						self.curCords = new AMap.LngLat(res.longitude, res.latitude);
						self.curPos = [res.longitude, res.latitude];
						self.updateCurrentPointMarker();
					},
					(err) => {
						self.updateCurrentPointMarker();
					}
				);
			},
			getRegeocodeInfo1() {
				if (this.currPosition == undefined || this.currPosition.regeocode == undefined) return '';
				let tmp = '';
				try {
					tmp =
						this.currPosition.regeocode.aois.length != 0 ?
						this.currPosition.regeocode.aois[0].name :
						this.currPosition.regeocode.crosses.length != 0 ?
						this.currPosition.regeocode.addressComponent.township + this.currPosition.regeocode.crosses[0].second_name :
						this.currPosition.regeocode.addressComponent.township;
				} catch (e) {
					console.log(e);
					tmp = '';
				}
				return tmp;
			},
			getRegeocodeInfo2() {
				if (this.currPosition == undefined || this.currPosition.regeocode == undefined) return '';
				let tmp = '';
				try {
					tmp = this.currPosition.regeocode.addressComponent.province + '' + this.currPosition.regeocode.addressComponent.district;
				} catch (e) {
					console.log(e);
					tmp = '';
				}
				return tmp;
			},
			mergeCurrent() {
				let self = this;
				if (!self.positionPicker) return;
				if (self.curPos) {
					self.positionPicker.start(new AMap.LngLat(self.curPos[0], self.curPos[1]));
					self.setNewPosition({
						lng: self.curPos[0],
						lat: self.curPos[1],
					});
				} else {
					self.$deviceApi.geolocation().then(
						(res) => {
							self.curCords = new AMap.LngLat(res.longitude, res.latitude);
							self.curPos = [res.longitude, res.latitude];

							self.updateCurrentPointMarker();
							self.positionPicker.start(new AMap.LngLat(self.curPos[0], self.curPos[1]));
							self.setNewPosition({
								lng: self.curPos[0],
								lat: self.curPos[1],
							});
						},
						(err) => {
							self.$u.toast('定位失败');
							self.updateCurrentPointMarker();
						}
					);
				}
			},
			async confirm() {
				// 限制经纬与默认经纬度一致 导致数据问题 fsx 2024-3-8 开始
				let curCords = [this.currPosition.longitude, this.currPosition.latitude]
                if(JSON.stringify(SET_MAP_LAT_LON) === JSON.stringify(curCords)){
                    return this.$modal.alert('请拖动图标调整位置');
                }
				// 限制经纬与默认经纬度一致 导致数据问题 fsx 2024-3-8 开始
				
				// 当前位置信息截图生成经营场所方位图  fsx 2024-2-23 开始
				let url = "";
				if(this.isScreenshot){
					// 截图模块
					let canvasBox = document.querySelector('#container') || null
					let scrollTop = document.documentElement.scrollTop
					// 左侧计算方法， 元素距离屏幕左侧的距离
					let canvasBoxOffsetLeft = canvasBox ? canvasBox.getBoundingClientRect().left : 0;
					// 顶部计算方法， 元素距离顶部距离 + body滚动高度
					let canvasBoxOffsetTop = canvasBox ? canvasBox.offsetTop + scrollTop : 0;
					
					try {
						// await接收图片地址 
						url = await screenshots({
							canvasBox,
							canvasBoxOffsetLeft,
							canvasBoxOffsetTop
						})
					} catch(err) {
						console.log("err",err)
					}
				}
				// 当前位置信息截图生成经营场所方位图  fsx 2024-2-23 结束
				if (this.canDrag == true) {
					// 当前位置信息截图生成经营场所方位图 返回调用页面，并且返回是否截图配置项isScreenshot fsx 2024-2-23 开始
					let params = Object.assign(this.currPosition,{imgData:url,isScreenshot:this.isScreenshot})
					this.backPrev({
						paramKey: 'pos',
						param: params,
					});
					// 当前位置信息截图生成经营场所方位图 返回调用页面，并且返回是否截图配置项isScreenshot fsx 2024-2-23 结束
				} else {
					this.backPrev({
						paramKey: 'pos',
						param: {
							latitude: this.curPos[1],
							longitude: this.curPos[0],
						},
					});
				}
			},
			setMapInstance(cords) {
				let self = this;
				if (!self.hasInited) return;
				self.curCords = new AMap.LngLat(cords[0], cords[1]);
				self.amap = new AMap.Map('container', {
					center: self.curCords,
					showControlButton: true,
					zoom: 18,
				});
				self.setCurrentPointMarker();
				self.$modal.hideLoading();
				if (self.canDrag == true) {
					AMapUI.loadUI(['misc/PositionPicker'], function(PositionPicker) {
						AMap.PositionPicker = PositionPicker;
						self.loadMarkList();
					});
				} else {
					self.setNewPosition({
						lng: self.curPos[0],
						lat: self.curPos[1],
					});
				}
			},
			setNewPosition(pos) {
				this.newPosition.lng = pos.lng + '';
				this.newPosition.lat = pos.lat + '';
			},
			loadMarkList() {
				let self = this;
				self.positionPicker = new AMap.PositionPicker({
					mode: 'dragMarker',
					map: self.amap,
					iconStyle: {
						url: require('@/static/market/new-location.png'),
						ancher: [20, 55],
						size: [20, 30],
					},
				});
				self.amap.on('click', function(positionResult) {
					self.disable = false;
					self.positionPicker.start(new AMap.LngLat(positionResult.lnglat.getLng(), positionResult.lnglat.getLat()));
				});
				// 选点功过
				self.positionPicker.on('success', function(positionResult) {
					self.currPosition = {
						accuracy: 0,
						altitude: 0,
						altitudeAccuracy: null,
						heading: null,
						latitude: positionResult.position.getLat(),
						longitude: positionResult.position.getLng(),
						speed: null,
						detailAddress: positionResult['address'],
						regeocode: positionResult.regeocode,
						// hasMarket:self.hasMarket,
					};
					if (self.step == 'start') {
						self.disable = true;
					}
					self.setNewPosition({
						lng: positionResult.position.getLng(),
						lat: positionResult.position.getLat(),
					});
				});
				self.positionPicker.on('fail', function(positionResult) {
					console.log('获取点坐标失败');
				});
				if (self.oldPosition.lng && self.oldPosition.lat && Number(self.oldPosition.lng) != 0 && Number(self.oldPosition.lat) != 0) {
					self.positionPicker.start(new AMap.LngLat(self.oldPosition.lng, self.oldPosition.lat));
				} else {
					if (self.curPos) {
						self.positionPicker.start(new AMap.LngLat(self.curPos[0], self.curPos[1]));
						self.setNewPosition({
							lng: self.curPos[0],
							lat: self.curPos[1],
						});
					}
				}
				self.amap.panBy(0, 1);
			},
			justInitMap() {
				this.$modal.alert('请在设备的设置中开启APP的定位权限后重新获取当前位置');
				this.amap = new AMap.Map('container', {
					showControlButton: true,
					zoom: 18,
				});
				let self = this;
				this.$modal.hideLoading();
				AMapUI.loadUI(['misc/PositionPicker'], function(PositionPicker) {
					AMap.PositionPicker = PositionPicker;
					self.loadMarkList();
				});
			},
		},
	};
</script>

<style scoped lang="scss">
	uni-page-body {
		min-height: 100%;
		width: 100%;
		background-color: #f1f0f6;
	}

	.page {
		padding: 0;
	}

	.right-icon {
		padding: 0 25rpx;
		font-size: 30rpx;
		color: white;
	}

	#container {
		/* #ifdef H5 */
		width: 100%;
		height: 100%;
		/* #endif */
		/* #ifdef APP-PLUS */
		height: calc(100vh - 44 - var(--status-bar-height));
		margin-top: calc(44 + var(--status-bar-height));
		/* #endif */
	}

	.retailer-markers {
		width: 30%;
		position: absolute;
		top: calc(84px + env(safe-area-inset-top));
		z-index: 888;
		line-height: 38rpx;
		background-color: rgba(255, 255, 255, 1);
		margin: 0 10px;
		padding: 20rpx 20rpx;
		border-radius: 10px;
	}

	.markers-state {
		font-size: 28rpx;
		margin: 0 10rpx;
		background-color: rgba(255, 255, 255, 1);
		display: inline-flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		width: 100%;
	}

	.index-class {
		font-weight: bold;
	}

	.poi-info {
		color: #666;
		line-height: 25px;
		margin: 5px 0px;
		width: 100%;
		display: inline-flex;
		flex-direction: column;
		font-size: 28rpx;
		margin-bottom: 5rpx;
	}

	.poi-name {
		margin: 3rpx 0rpx;
	}

	.poi-price {
		display: inline-flex;
		flex-direction: row;
		align-items: center;
		margin: 3rpx 0rpx;
	}

	.poi-price-txt {
		margin-left: 28rpx;
	}

	.poi-title {
		color: black;
		font-size: 32rpx;
	}

	.task-status-lst {
		line-height: 38rpx;
		margin: 10px;
		display: flex;
		flex-direction: row;
		align-items: center;
	}

	.item-circle-status {
		width: 4px;
		height: 16px;
		border-radius: 20%;
	}

	.item-color {
		color: #999;
		margin-left: 15px;
	}

	.cur-loc {
		position: absolute;
		bottom: 20px;
		left: 15px;
		padding: 5px;
		background: #fff;
		width: 35px;
		height: 35px;
		box-shadow: 0px 0px 0px 1px #ddd;
	}

	.merge-loc {
		position: absolute;
		bottom: 60px;
		left: 15px;
		padding: 5px;
		background: #fff;
		width: 35px;
		height: 35px;
		box-shadow: 0px 0px 0px 1px #ddd;
	}

	.m-market {
		position: fixed;
		border-radius: 34rpx;
		bottom: 40rpx;
		margin: auto;
		left: 20rpx;
		right: 20rpx;
		z-index: 100;
		background-color: #ffffff;
	}

	.padding-13 {
		padding: 36rpx 26rpx;
		font-size: 32rpx;
	}

	.pt-13 {
		padding: 0 26rpx 26rpx;
		font-size: 24rpx;
	}

	.y-location {
		padding: 10rpx;
		width: 150px;
		background: #fff;
		display: inline-flex;
		align-items: center;
		flex-direction: column;
		box-shadow: 0.5px 0.5px 0.5px rgba(0, 0, 0, 0.3);
		position: absolute;
		top: calc(84px + env(safe-area-inset-top));
		right: 10px;
		font-size: 14px;

		uni-text {
			margin: 5px;
		}
	}
</style>
